package com.bank.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.bank.entity.CardInfo;
import com.bank.entity.UserInfo;
import com.bank.service.CardInfoService;
import com.bank.service.UserInfoService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import java.util.List;
import java.util.stream.Collectors;
import java.nio.charset.StandardCharsets;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpSession;
import com.bank.entity.Transaction;
import com.bank.service.TransactionService;
import java.util.Date;
import org.springframework.transaction.annotation.Transactional;
import com.bank.service.DepositService;
import com.bank.entity.Deposit;
import java.util.Optional;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private CardInfoService cardInfoService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private TransactionService transactionService;
    @Autowired
    private DepositService depositService;

    @GetMapping("/login")
    public String login() {
        return "user/login";
    }

    @PostMapping("/login")
    public String doLogin(String cardID, String password, Model model, HttpSession session) {
        CardInfo card = cardInfoService.findById(cardID).orElse(null);
        if (card == null || !card.getPass().equals(password) || "挂失".equals(card.getIsReportLoss())) {
            model.addAttribute("error", "卡号或密码错误，或该卡已挂失！");
            return "user/login";
        }
        UserInfo user = userInfoService.findById(card.getCustomerID()).orElse(null);
        model.addAttribute("user", user);
        model.addAttribute("card", card);
        session.setAttribute("cardId", card.getCardID());
        return "redirect:/user/main";
    }

    @GetMapping("/main")
    public String main(Model model, HttpSession session) {
        String cardId = (String) session.getAttribute("cardId");
        if (cardId == null) {
            return "redirect:/user/login";
        }
        CardInfo card = cardInfoService.findById(cardId).orElse(null);
        if (card == null) {
            return "redirect:/user/login";
        }
        UserInfo user = userInfoService.findById(card.getCustomerID()).orElse(null);
        
        String savingName = "未知类型";
        if (card.getSavingID() != null) {
            Optional<Deposit> depositOpt = depositService.findById(card.getSavingID());
            if (depositOpt.isPresent()) {
                savingName = depositOpt.get().getSavingName();
            }
        }

        model.addAttribute("user", user);
        model.addAttribute("card", card);
        model.addAttribute("savingName", savingName);
        model.addAttribute("recentTrades", transactionService.findRecentByCardID(cardId));
        return "user/main";
    }

    @GetMapping("/deposit")
    public String depositPage() { return "user/deposit"; }

    @PostMapping("/deposit")
    @Transactional
    public String doDeposit(Double amount, Model model, HttpSession session) {
        try {
            String cardID = (String) session.getAttribute("cardId");
            if (cardID == null) {
                model.addAttribute("error", "会话已过期，请重新登录");
                return "redirect:/user/login";
            }
            
            CardInfo card = cardInfoService.findById(cardID).orElse(null);
            if (card == null) {
                model.addAttribute("error", "卡号不存在");
                return "user/deposit";
            }
            
            if (amount == null || amount <= 0) {
                model.addAttribute("error", "金额无效");
                return "user/deposit";
            }
            
            // 检查卡是否挂失
            if ("挂失".equals(card.getIsReportLoss())) {
                model.addAttribute("error", "该卡已挂失，无法存款");
                return "user/deposit";
            }
            
            // 执行存款操作
            card.setBalance(card.getBalance() + amount);
            cardInfoService.save(card);
            
            // 记录交易
            Transaction t = new Transaction();
            t.setCardID(cardID);
            t.setTradeType("存款");
            t.setTradeMoney(amount);
            t.setTradeDate(new Date());
            t.setRemark("余额：" + card.getBalance());
            transactionService.insertTrade(t);
            
            model.addAttribute("success", "存款成功，当前余额：" + card.getBalance());
            return "user/deposit";
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "存款操作失败：" + e.getMessage());
            return "user/deposit";
        }
    }

    @GetMapping("/withdraw")
    public String withdrawPage() { return "user/withdraw"; }

    @PostMapping("/withdraw")
    @Transactional
    public String doWithdraw(Double amount, Model model, HttpSession session) {
        try {
            String cardID = (String) session.getAttribute("cardId");
            if (cardID == null) {
                model.addAttribute("error", "会话已过期，请重新登录");
                return "redirect:/user/login";
            }
            
            CardInfo card = cardInfoService.findById(cardID).orElse(null);
            if (card == null) {
                model.addAttribute("error", "卡号不存在");
                return "user/withdraw";
            }
            
            if (amount == null || amount <= 0) {
                model.addAttribute("error", "金额无效");
                return "user/withdraw";
            }
            
            if (card.getBalance() < amount) {
                model.addAttribute("error", "余额不足，当前余额：" + card.getBalance());
                return "user/withdraw";
            }
            
            // 检查卡是否挂失
            if ("挂失".equals(card.getIsReportLoss())) {
                model.addAttribute("error", "该卡已挂失，无法取款");
                return "user/withdraw";
            }
            
            // 执行取款操作
            card.setBalance(card.getBalance() - amount);
            cardInfoService.save(card);
            
            // 记录交易
            Transaction t = new Transaction();
            t.setCardID(cardID);
            t.setTradeType("取款");
            t.setTradeMoney(amount);
            t.setTradeDate(new Date());
            t.setRemark("余额：" + card.getBalance());
            transactionService.insertTrade(t);
            
            model.addAttribute("success", "取款成功，当前余额：" + card.getBalance());
            return "user/withdraw";
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "取款操作失败：" + e.getMessage());
            return "user/withdraw";
        }
    }

    @GetMapping("/transfer")
    public String transferPage() { return "user/transfer"; }

    @PostMapping("/transfer")
    @Transactional
    public String doTransfer(String fromCardID, String toCardID, Double amount, String password, Model model, HttpSession session) {
        try {
            // 验证会话中的卡号
            String sessionCardID = (String) session.getAttribute("cardId");
            if (sessionCardID == null) {
                model.addAttribute("error", "会话已过期，请重新登录");
                return "redirect:/user/login";
            }
            
            // 验证转出卡是否为当前登录用户的卡
            if (!sessionCardID.equals(fromCardID)) {
                model.addAttribute("error", "只能转账自己的卡");
                return "user/transfer";
            }
            
            CardInfo fromCard = cardInfoService.findById(fromCardID).orElse(null);
            CardInfo toCard = cardInfoService.findById(toCardID).orElse(null);
            
            if (fromCard == null || toCard == null) {
                model.addAttribute("error", "卡号不存在");
                return "user/transfer";
            }
            
            if (amount == null || amount <= 0) {
                model.addAttribute("error", "金额无效");
                return "user/transfer";
            }
            
            if (!fromCard.getPass().equals(password)) {
                model.addAttribute("error", "支付密码错误");
                return "user/transfer";
            }
            
            if (fromCard.getBalance() < amount) {
                model.addAttribute("error", "余额不足，当前余额：" + fromCard.getBalance());
                return "user/transfer";
            }
            
            if ("挂失".equals(fromCard.getIsReportLoss()) || "挂失".equals(toCard.getIsReportLoss())) {
                model.addAttribute("error", "有卡已挂失，无法转账");
                return "user/transfer";
            }
            
            // 执行转账操作
            fromCard.setBalance(fromCard.getBalance() - amount);
            toCard.setBalance(toCard.getBalance() + amount);
            cardInfoService.save(fromCard);
            cardInfoService.save(toCard);
            
            // 记录转出交易
            Transaction t1 = new Transaction();
            t1.setCardID(fromCardID);
            t1.setTradeType("转出");
            t1.setTradeMoney(amount);
            t1.setTradeDate(new Date());
            t1.setRemark("余额：" + fromCard.getBalance());
            transactionService.insertTrade(t1);
            
            // 记录转入交易
            Transaction t2 = new Transaction();
            t2.setCardID(toCardID);
            t2.setTradeType("转入");
            t2.setTradeMoney(amount);
            t2.setTradeDate(new Date());
            t2.setRemark("余额：" + toCard.getBalance());
            transactionService.insertTrade(t2);
            
            model.addAttribute("success", "转账成功，您的余额：" + fromCard.getBalance());
            return "user/transfer";
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "转账操作失败：" + e.getMessage());
            return "user/transfer";
        }
    }

    @GetMapping("/query")
    public String queryPage() { return "user/query"; }

    @PostMapping("/query")
    public String doQuery(Model model, HttpSession session) {
        try {
            String cardID = (String) session.getAttribute("cardId");
            if (cardID == null) {
                model.addAttribute("error", "会话已过期，请重新登录");
                return "redirect:/user/login";
            }
            
            CardInfo card = cardInfoService.findById(cardID).orElse(null);
            if (card == null) {
                model.addAttribute("error", "卡号不存在");
                return "user/query";
            }
            
            model.addAttribute("balance", card.getBalance());
            return "user/query";
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "查询失败：" + e.getMessage());
            return "user/query";
        }
    }

    @GetMapping("/security")
    public String securityPage() { return "user/security"; }

    @PostMapping("/security")
    @Transactional
    public String doSecurity(String cardID, String action, String oldPassword, String newPassword, Model model, HttpSession session) {
        try {
            // 验证会话中的卡号
            String sessionCardID = (String) session.getAttribute("cardId");
            if (sessionCardID == null) {
                model.addAttribute("error", "会话已过期，请重新登录");
                return "redirect:/user/login";
            }
            
            // 验证操作的卡是否为当前登录用户的卡
            if (!sessionCardID.equals(cardID)) {
                model.addAttribute("error", "只能操作自己的卡");
                return "user/security";
            }
            
            CardInfo card = cardInfoService.findById(cardID).orElse(null);
            if (card == null) {
                model.addAttribute("error", "卡号不存在");
                return "user/security";
            }
            
            if ("loss".equals(action)) {
                card.setIsReportLoss("挂失");
                cardInfoService.save(card);
                model.addAttribute("success", "挂失成功");
            } else if ("unloss".equals(action)) {
                card.setIsReportLoss("正常");
                cardInfoService.save(card);
                model.addAttribute("success", "解挂成功");
            } else if ("changePwd".equals(action)) {
                if (!card.getPass().equals(oldPassword)) {
                    model.addAttribute("error", "原密码错误");
                    return "user/security";
                }
                card.setPass(newPassword);
                cardInfoService.save(card);
                model.addAttribute("success", "密码修改成功");
            }
            return "user/security";
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "操作失败：" + e.getMessage());
            return "user/security";
        }
    }

    // 客户列表
    @GetMapping("/list")
    public String list(Model model) {
        List<UserInfo> users = userInfoService.findAll();
        model.addAttribute("users", users);
        return "user/list";
    }

    // 编辑客户信息页面
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        UserInfo user = userInfoService.findById(id).orElse(null);
        model.addAttribute("user", user);
        return "user/edit";
    }

    // 提交编辑
    @PostMapping("/edit")
    @Transactional
    public String doEdit(@ModelAttribute UserInfo user) {
        userInfoService.save(user);
        return "redirect:/user/list";
    }

    // 删除客户
    @GetMapping("/delete/{id}")
    @Transactional
    public String delete(@PathVariable Long id) {
        userInfoService.deleteById(id);
        return "redirect:/user/list";
    }

    // 导出客户CSV
    @GetMapping("/export")
    @ResponseBody
    public ResponseEntity<byte[]> exportCsv() {
        List<UserInfo> users = userInfoService.findAll();
        StringBuilder sb = new StringBuilder("客户编号,姓名,身份证号,电话,地址\n");
        for (UserInfo u : users) {
            sb.append(u.getCustomerID()).append(",")
              .append(u.getCustomerName()).append(",")
              .append(u.getPid()).append(",")
              .append(u.getTelephone()).append(",")
              .append(u.getAddress()).append("\n");
        }
        byte[] csvBytes = sb.toString().getBytes(StandardCharsets.UTF_8);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "users.csv");
        return ResponseEntity.ok().headers(headers).body(csvBytes);
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/";
    }
} 